//
//  AppDelegate+JPUSH.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/8/8.
//

import Foundation
import YPBedrock

let JiGuangAppId = "89ccc9bee437e0d639b6dac7"

extension AppDelegate {
    /// 初始化极光
    func configJiGuang(_ application: UIApplication,
                       launchOptions: [UIApplication.LaunchOptionsKey: Any]?)
    {
        registerJMLink()
        registerJPush(application, launchOptions: launchOptions)

        WmcAppStateManager.shared.becomeActive.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.clearIconBadgeNumber()
        }).disposed(by: rx.disposeBag)
    }

    /// 注册极光推送
    private func registerJPush(_ application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        var apsForProduction: Bool = true
        #if DEBUG
            apsForProduction = false
        #endif

        JPUSHService.setup(withOption: launchOptions,
                           appKey: JiGuangAppId,
                           channel: channel,
                           apsForProduction: apsForProduction)

        let entity = JPUSHRegisterEntity()
        if #available(iOS 12.0, *) {
            entity.types =
                Int(JPAuthorizationOptions.alert.rawValue) |
                Int(JPAuthorizationOptions.badge.rawValue) |
                Int(JPAuthorizationOptions.sound.rawValue) |
                Int(JPAuthorizationOptions.providesAppNotificationSettings.rawValue)
        } else {
            entity.types =
                Int(JPAuthorizationOptions.alert.rawValue) |
                Int(JPAuthorizationOptions.badge.rawValue) |
                Int(JPAuthorizationOptions.sound.rawValue)
        }

        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
//
        JPUSHService.registrationIDCompletionHandler { resCode, registrationID in
            if let id = registrationID {
                // 水印相机后台注册
                WmcOtherAPI.registerPush(token: id)
            }
        }
    }

    /// 注册设备标识
    func JPushRegisterDeviceToken(deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }

    /// 注册极光魔链
    private func registerJMLink() {
        let config = JMLinkConfig()
        config.appKey = JiGuangAppId
        config.advertisingId = nil
        #if DEBUG
            config.isProduction = false
        #else
            config.isProduction = true
        #endif
        JMLinkService.setup(with: config)

        // 不使用剪贴板
        JMLinkService.pasteBoardEnable(false)

        // 注册通用的的获取参数回调方法
        JMLinkService.registerHandler { [weak self] response in
            guard let weakSelf = self else { return }
            guard let params = response?.params else { return }
            weakSelf.jiGuangLog("收到参数：\(params)")
            // 拿到参数后，根据自身项目参数协议解析，处理跳转逻辑
            DispatchQueue.main.async { // 通过协议解耦发送消息到监听者
                WmcNotice.Post(WmcJMLinkActionProtocol.self) { obj in
                    obj.jmLinkReceived(with: params)
                }
            }
        }

        // 获取无码邀请中传回来的相关值
        JMLinkService.getMLinkParam(nil) { params in
        }
    }

    /// 通过universal link来唤起app
    func jmLinkHandleOpenUniversalLink(_ application: UIApplication,
                                       continue userActivity: NSUserActivity,
                                       restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool
    {
        return JMLinkService.continue(userActivity)
    }

    /// iOS9+，通过url scheme来唤起app
    func jmLinkHandleOpen(_ app: UIApplication,
                          open url: URL,
                          options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool
    {
        return JMLinkService.routeMLink(url)
    }

    /// 清空徽标数值
    private func clearIconBadgeNumber() {
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
    }
}

// MARK: - 扩展AppDelegate + JPUSHRegisterDelegate

extension AppDelegate: JPUSHRegisterDelegate {
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo = notification.request.content.userInfo
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
            jiGuangLog("应用在前台收到消息:\(userInfo)")
        }
    }

    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let userInfo = response.notification.request.content.userInfo
        jiGuangLog("应用在前台收到消息:\(userInfo)")
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 系统要求执行这个方法
        completionHandler()
    }

    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {}

    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable: Any]!) {}

    /// 日志系统
    fileprivate func jiGuangLog(_ log: String) {
        WmcLogManager.DebugLog(type: .jiGuang, log: log)
    }
}
